#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import re
import mrget
import shutil
import sqlglot
import tempfile
import contextlib
import subprocess


class Util:

    @staticmethod
    def sqliteCheckTables(dbConn, sql):
        for item in sqlglot.parse(sql):
            # FIXME
            pass

        # FIXME: should do extensively check
        for m in re.finditer(r"CREATE TABLE (.*) \(", sql):
            tableName = m.group(1)
            c = dbConn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (tableName,))
            if c.fetchone() is None:
                return False
        return True

    @staticmethod
    def listIn(list1, list2):
        for item in list1:
            if item not in list2:
                return False
        return True

    @staticmethod
    def dictSingleGet(dictObj):
        for k, v in dictObj.items():
            return (k, v)

    @staticmethod
    def splitToTuple(s, d, count):
        ret = s.split(d)
        assert len(ret) == count
        return tuple(ret)

    @staticmethod
    def sqliteHasTables(dbConn, *tableNames):
        c = dbConn.cursor()
        for tableName in tableNames:
            c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (tableName,))
            if c.fetchone() is None:
                return False
        return True

    @staticmethod
    def toSeconds(desc):
        if re.fullmatch("[0-9]+s", desc):
            # seconds
            return int(desc)
        elif re.fullmatch("[0-9]+m", desc):
            # minutes
            return int(desc) * 60
        elif re.fullmatch("[0-9]+h", desc):
            # hours
            return int(desc) * 3600
        elif re.fullmatch("[0-9]+d", desc):
            # days
            return int(desc) * 3600 * 24
        elif re.fullmatch("[0-9]+w", desc):
            # weeks
            return int(desc) * 3600 * 24 * 7
        else:
            # no months, years, they can't be converted to seconds easily
            assert False

    @staticmethod
    def forceDelete(*pathList):
        for path in pathList:
            if os.path.islink(path):
                os.remove(path)
            elif os.path.isfile(path):
                os.remove(path)
            elif os.path.isdir(path):
                shutil.rmtree(path)
            elif os.path.lexists(path):
                os.remove(path)             # other type of file, such as device node
            else:
                pass                        # path does not exist, do nothing

    @staticmethod
    def removeEmptyDir(path):
        if len(os.listdir(path)) == 0:
            os.rmdir(path)

    @staticmethod
    def forceMakeEmptyDir(path):
        if not os.path.exists(path):
            os.mkdir(path)
        elif os.path.islink(path) or not os.path.isdir(path):
            Util.forceDelete(path)
            os.mkdir(path)
        else:
            for fn in os.listdir(path):
                Util.forceDelete(os.path.join(path, fn))

    @contextlib.contextmanager
    @staticmethod
    def mountHttpDir(url, parentDir=None):
        if url.startswith("mirror://"):
            url = mrget.target_urls(url)[0]

        with tempfile.NamedTemporaryFile(dir=parentDir, delete_on_close=False) as tmpf:
            tmpf.write(b'')
            tmpf.close()
            with tempfile.TemporaryDirectory(dir=parentDir) as mntDir:
                subprocess.check_call(["httpdirfs", "--config", tmpf.name, url, mntDir])
                try:
                    yield mntDir
                finally:
                    subprocess.check_call(["umount", mntDir])


class TempChdir:

    def __init__(self, dirname):
        self.olddir = os.getcwd()
        os.chdir(dirname)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        os.chdir(self.olddir)
